﻿using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;
using ProxyServer.Certs;
using ProxyServer.Entities;
using ProxyServer.EntityFrameworkCore.ValueConverts;
using Yarp.ReverseProxy.Configuration;

namespace ProxyServer.EntityFrameworkCore
{
    public class AppDbContext : DbContext
    {
        private readonly ModelBuilderOptions<AppDbContext> _modelCreating;

        public AppDbContext(DbContextOptions<AppDbContext> options, ModelBuilderOptions<AppDbContext>? modelCreating) : base(options)
        {
            _modelCreating = modelCreating ?? throw new ArgumentNullException(nameof(modelCreating));
        }

        public DbSet<ServiceEntity> Services => Set<ServiceEntity>();
        public DbSet<ProxyConfigSnapshotEntity> Snapshots => Set<ProxyConfigSnapshotEntity>();
        public DbSet<CertificateInfo> CertificateInfos => Set<CertificateInfo>();


        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);

            _modelCreating?.ConfigureModel(modelBuilder);
            // var services = modelBuilder.Entity<ServiceEntity>();
            // services.HasKey(x => x.Id);
            // services.HasIndex(x => x.Name).IsUnique();
            // services.Property(x => x.Created).HasConversion(LocalDateTimeOffsetValueConverter.Singleton);
            // services.Property(x => x.LastModified).HasConversion(LocalDateTimeOffsetValueConverter.Singleton);
            // services.Property(x => x.Endpoints).HasConversion(new JsonStringValueConverter<List<ServiceEndpointEntity>>([]));

            // var snapshots = modelBuilder.Entity<ProxyConfigSnapshotEntity>();
            // snapshots.HasKey(x => x.Id);
            // snapshots.Property(x => x.Routes).HasConversion(new JsonStringValueConverter<List<RouteConfig>>([]));
            // snapshots.Property(x => x.Clusters).HasConversion(new JsonStringValueConverter<List<ClusterConfig>>([]));
            // snapshots.Property(x => x.AppliedAt).HasConversion(LocalDateTimeOffsetValueConverter.Singleton);
            // snapshots.Property(x => x.RemovedAt).HasConversion(LocalDateTimeOffsetValueConverter.Singleton);
        }
    }
}
